/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.service.reliable.impl;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import cgl.narada.event.EventID;
import cgl.narada.event.NBEvent;
import cgl.narada.matching.Profile;
import cgl.narada.service.ServiceException;
import cgl.narada.service.client.NBRecoveryNotification;
import cgl.narada.service.client.impl.EventConsumerImpl;
import cgl.narada.service.qos.ConsumerConstraints;
import cgl.narada.service.qos.QosEvent;
import cgl.narada.service.qos.impl.QosServiceImpl;
import cgl.narada.service.reliable.events.RdArchivalServiceNotification;
import cgl.narada.service.reliable.events.RdProfileUpdateRequest;
import cgl.narada.service.reliable.events.RdProfileUpdateResponse;
import cgl.narada.service.reliable.events.RdRecoveryEntityRequest;
import cgl.narada.service.reliable.events.RdRecoveryResponse;
import cgl.narada.service.reliable.events.RdRetransmissionServiceEvent;

/** This class provides a set of core functions that service implementations
 need to satisfy. All services within the system need to conform to this
 interface. 

 @author Shrideep Pallickara
 $Date$
 $Revision$
 */

public class RdEntityActuatorImpl implements RdDebugFlags {

    private Hashtable      subscriberPercolators;

    private Hashtable      reliablyRegisteredProfiles;

    private Hashtable      profileUpdates;

    private String         moduleName = "RdEntityActuatorImpl: ";

    /** When we received retransmitted event, we first need to reconstruct
     the qosEvent associated with the nbEvent. Since this is asynchronous
     we put the archival notification in the pending buffer before
     we release it upon arrival of the retransmitted event 
     eventId -> archivalNotification
     */
    private Hashtable      pendingNotifications;

    private QosServiceImpl qosServiceImpl;

    public RdEntityActuatorImpl(QosServiceImpl qosServiceImpl) {
        this.qosServiceImpl = qosServiceImpl;

        subscriberPercolators = new Hashtable();

        pendingNotifications = new Hashtable();

        reliablyRegisteredProfiles = new Hashtable();

        profileUpdates = new Hashtable();
    }

    public void terminateService() throws ServiceException {
        if (subscriberPercolators.size() == 0) {
            return;
        }

        Enumeration e = subscriberPercolators.elements();

        while (e.hasMoreElements()) {
            SubscriberPercolator _percolator = (SubscriberPercolator) e
                    .nextElement();
            _percolator.terminateService();
        }

    }

    public void processRetransmittedEvent(
            RdRetransmissionServiceEvent retransmittedEvent)
            throws ServiceException {

        NBEvent nbEvent = retransmittedEvent.getEvent();
        RdArchivalServiceNotification archNotification = retransmittedEvent
                .getArchivalNotification();

        EventID eventId = nbEvent.getEventHeaders().getEventId();

        if (pendingNotifications.containsKey(eventId)) {
            return;
        }
        /** Wait for the nbEvent to be wrapped inside a QosEvent by the 
         qosServiceImpl */
        pendingNotifications.put(eventId, archNotification);

        /** Proceed to create a QosEvent wrapping for the event */
        qosServiceImpl.processReceivedEvent(nbEvent);
    }

    /** Upong receipt of a NORMAL nbEvent, the qosService constructs a QosEvent
     if there were any consumerConstraints specified. This event is then
     routed here pending satisfaction of consumer constraints */
    public void processConstructedQosEvent(QosEvent qosEvent)
            throws ServiceException {
        if (RdEntityActuatorImpl_Debug) {
            System.out.println(moduleName + "Got constructed QosEvent");
        }
        EventID eventId = qosEvent.getEventId();
        RdArchivalServiceNotification archNotification = null;
        if (pendingNotifications.containsKey(eventId)) {
            /** This is a retransmitted event whose QosEvent was being constructed
             in the qosServiceImpl */
            archNotification = (RdArchivalServiceNotification) pendingNotifications
                    .get(eventId);
        }

        ConsumerConstraints[] pendingOnes = qosEvent
                .getPendingConsumerConstraints();

        if (pendingOnes == null) {
            System.out.println(moduleName
                    + "ALL Consumer Constraints satisfied "
                    + " WHY was event routed here?!");
            return;
        }

        if (pendingOnes.length == 1) {
            int entityId = pendingOnes[0].getEntityId();
            Object entityKey = new Integer(entityId);
            routeQosEventToEntity(entityKey, qosEvent, archNotification);
            return;
        }

        /** If there are more than one pending consumer constraints for the
         qosEvent, more involved processing is needed. Specifically, we
         need to determine all the entity-ids which has unsatisfied
         constraints and then proceed to route to the corresponding
         subscriber percolators */
        Vector entityVec = new Vector();
        for (int i = 0; i < pendingOnes.length; i++) {
            Object tempKey = new Integer(pendingOnes[i].getEntityId());

            if (!entityVec.contains(tempKey)) {
                entityVec.addElement(tempKey);
            }
        }

        for (int i = 0; i < entityVec.size(); i++) {
            routeQosEventToEntity(entityVec.elementAt(i), qosEvent,
                    archNotification);
        }
    }

    /** This method routes a given qosEvent and its accompanying notification
     event to the appropriate subscriber percolators */
    private void routeQosEventToEntity(Object entityKey, QosEvent qosEvent,
            RdArchivalServiceNotification archNotification)
            throws ServiceException {
        int entityId = ((Integer) entityKey).intValue();
        if (!subscriberPercolators.containsKey(entityKey)) {
            subscriberPercolators.put(entityKey, new SubscriberPercolator(
                    entityId, this));
        }

        SubscriberPercolator percolator = (SubscriberPercolator) subscriberPercolators
                .get(entityKey);

        percolator.processReceivedEvent(qosEvent);

        if (archNotification != null) {
            percolator.processArchivalNotification(archNotification);
        }

    }

    public void qosEventAvailableForRelease(QosEvent qosEvent,
            RdArchivalServiceNotification archNotification) {
        if (RdEntityActuatorImpl_Debug) {
            System.out.println(moduleName + "QosEvent with accompanying "
                    + archNotification + " READY for release");
        }
        qosServiceImpl.onReliableDelivery(qosEvent, archNotification);
    }

    public void syncPointHasBeenAdvanced(int entityId, int templateId,
            long advanceSync) {
        if (RdEntityActuatorImpl_Debug) {
            System.out.println(moduleName + "Sync point has been advanced for "
                    + "entity=" + entityId + ", templateId=" + templateId
                    + " to SYNC-POINT=" + advanceSync);
        }
        qosServiceImpl.onAdvanceOfSyncpoint(entityId, templateId, advanceSync);

    }

    public void processArchivalNotificationForEntity(Object entityKey,
            RdArchivalServiceNotification archNotification)
            throws ServiceException {
        int entityId = ((Integer) entityKey).intValue();

        if (!subscriberPercolators.containsKey(entityKey)) {
            subscriberPercolators.put(entityKey, new SubscriberPercolator(
                    entityId, this));
        }

        SubscriberPercolator percolator = (SubscriberPercolator) subscriberPercolators
                .get(entityKey);

        if (archNotification != null) {
            percolator.processArchivalNotification(archNotification);
        }
    }

    public void issueRecoveryRequest(RdRecoveryEntityRequest recoveryRequest)
            throws ServiceException {
        int entityId = recoveryRequest.getEntityId();
        Object entityKey = new Integer(entityId);

        if (!subscriberPercolators.containsKey(entityKey)) {
            subscriberPercolators.put(entityKey, new SubscriberPercolator(
                    entityId, this));
        }

        SubscriberPercolator percolator = (SubscriberPercolator) subscriberPercolators
                .get(entityKey);

        percolator.issueRecoveryRequest(recoveryRequest);

    }

    /** Subscribe the relevant consumer to the set of previously registered 
     profiles based on information encapsulated in the recovery response*/
    public void processRecoveryResponse(RdRecoveryResponse recoveryResponse)
            throws ServiceException {
        int entityId = recoveryResponse.getEntityId();
        int templateId = recoveryResponse.getTemplateId();
        long recoveryId = recoveryResponse.getRecoveryRequestId();

        String recoveringInfo = "";
        EventConsumerImpl recoveringConsumer;
        NBRecoveryNotification recoveryNotification;

        recoveringConsumer = qosServiceImpl.getRecoveringConsumer(recoveryId);
        if (recoveringConsumer == null) {
            System.out.println(moduleName
                    + "Unable to locate the recovering consumer");
            return;
        }

        if (!recoveryResponse.getSubscriberRecoveryInfo().containsProfileInfo()) {
            recoveringInfo = moduleName
                    + "No profiles were previously registered"
                    + " by entityId=" + entityId + " for templateId="
                    + templateId + "\n";
            recoveryNotification = new NBRecoveryNotification(recoveryId,
                    entityId, templateId, true, recoveringInfo);
            recoveringConsumer
                    .propagateRecoveryNotification(recoveryNotification);
            return;
        }

        Profile[] profiles = recoveryResponse.getSubscriberRecoveryInfo()
                .getRegisteredProfiles();
        recoveringInfo += "The following profiles were PREVIOUSLY registered\n";

        for (int i = 0; i < profiles.length; i++) {
            recoveringInfo += profiles[i].toString() + "\n";
            reliablyRegisteredProfiles.put(profiles[i].getProfileId(),
                    profiles[i]);
        }

        for (int i = 0; i < profiles.length; i++) {
            ConsumerConstraints constraints = recoveringConsumer
                    .createConsumerConstraints(profiles[i]);
            constraints.setReceiveReliably(templateId);
            try {
                recoveringConsumer.subscribeTo(profiles[i], constraints);
            } catch (ServiceException serEx) {
                System.out.println(moduleName + serEx);
            }
        }

        recoveringInfo += ("Entity has been automatically subscribed to all"
                + "previously registered profiles \n\n");
        recoveryNotification = new NBRecoveryNotification(recoveryId, entityId,
                templateId, true, recoveringInfo);
        recoveringConsumer.propagateRecoveryNotification(recoveryNotification);

    }

    /** end processRecoveryResponse() */

    public void issueProfileUpdateRequest(Profile profile, boolean addProfile,
            ConsumerConstraints consumerConstraints) throws ServiceException {
        int entityId = consumerConstraints.getEntityId();
        int templateId = consumerConstraints.getTemplateId();

        if (templateId == 0) {
            throw new ServiceException(moduleName
                    + "Invalid templateId=0 contained"
                    + " in profile update request");
        }

        Object profileKey = profile.getProfileId();

        if (reliablyRegisteredProfiles.containsKey(profileKey)) {
            System.out.println(moduleName + "This profile has been reliably"
                    + " registered previously");
            return;
        }

        Object requestKey = new Long(System.currentTimeMillis());
        while (profileUpdates.containsKey(requestKey)) {
            /** This ensures that every update has a different request associated
             with it */
            requestKey = new Long(System.currentTimeMillis());
        }
        long requestId = ((Long) requestKey).longValue();

        Object entityKey = new Integer(entityId);
        if (!subscriberPercolators.containsKey(entityKey)) {
            subscriberPercolators.put(entityKey, new SubscriberPercolator(
                    entityId, this));
        }

        SubscriberPercolator percolator = (SubscriberPercolator) subscriberPercolators
                .get(entityKey);

        RdProfileUpdateRequest profileUpdateRequest = new RdProfileUpdateRequest(
                templateId, entityId, profile, addProfile, requestId);
        profileUpdates.put(requestKey, profileUpdateRequest);

        percolator.issueProfileUpdateRequest(profileUpdateRequest);

    }

    public void processProfileUpdateResponse(
            RdProfileUpdateResponse profileUpdateResponse)
            throws ServiceException {
        RdProfileUpdateRequest profileUpdateRequest = profileUpdateResponse
                .getProfileUpdateRequest();

        long requestId = profileUpdateRequest.getRequestId();
        Profile profile = profileUpdateRequest.getProfile();
        boolean addProfile = profileUpdateRequest.isAddProfile();

        boolean success = profileUpdateResponse.getStatus();
        Object requestKey = new Long(requestId);

        String info = "";
        if (success) {
            if (addProfile) {
                reliablyRegisteredProfiles.put(profile.getProfileId(), profile);
                info += "The profile addition was successful ";
            } else {
                reliablyRegisteredProfiles.remove(profile.getProfileId());
                info += "The profile removal was successful ";
            }/* end addProfile */
            profileUpdates.remove(requestKey);

            info += profileUpdateResponse.getAdditionalInfo();
            System.out.println(info);
            return;
        }/* end success */

        info += "Profile update request was not successful \n";
        info += profileUpdateResponse.getAdditionalInfo();
        System.out.println(info);
    }

}

